<template>
  <div class="w-fill h-auto bg-[#1a2c38] min-375 text-white">
    <div class="flex w-full bg-[#213743] items-center mb-4">
      <div
        class="max-w-[1200px] px-4 xl:px-0 w-full m-auto flex justify-between items-center h-[60px] xl:h-[115px]"
      >
        <h1 class="text-[1rem] xl:text-[1.6rem] font-bold">
          {{ $t("page.navbar.favorites") }}
        </h1>
        <img
          class="w-[12rem] xl:w-[24rem]"
          src="../../assets/gams/group-banner-default.png"
          alt=""
        />
      </div>
    </div>
    <div
      class="w-full max-w-[1200px] px-4 xl:px-0 m-auto p-4 mb-4 items-center"
    >
      <Search />
      <div class="gameBox py-4" v-if="games.length != 0">
        <div class="item relative" v-for="(item, i) in games" :key="i">
          <div class="hover-img">
            <!-- <img
              @click="
                clickGame(item.link_url);
                addRecent(item);
              "
              v-lazy="item.img_url"
              class=""
              alt=""
            /> -->
            <div
              @click="
                clickGame(item.link_url);
                addRecent(item);
              "
              class="game_loading_div"
              :style="'background-image:url(' + item.img_url + ')'"
            ></div>
            <div class="mb absolute w-full rounded h-[30%] top-[-2px] left-0" />
            <div
              class="absolute top-2 right-2 cursor-pointer star"
              @click="clickStar(item)"
            >
              <svg-icon
                v-if="item.is_collect == 0"
                class="text-[28px] star1"
                name="星星1"
              />
              <svg-icon v-else class="text-[28px] star2" name="星星2" />
            </div>
          </div>

          <div class="flex items-center mt-2">
            <div
              class="greenpoint w-[6px] h-[6px] rounded-full bg-[#1fff20]"
            ></div>
            <div class="flex text-white text-xs ml-2">
              {{ item.play_num }}
              <span class="ml-1 text-[#b1bad3]">{{
                $t("page.casino.inplay")
              }}</span>
            </div>
          </div>
        </div>
      </div>
      <el-empty
        v-else
        :image-size="200"
        :description="$t('layer.activity.noData')"
      />
      <p v-if="games.length != 0" class="text-[#b1bad3] text-center">
        {{
          $t("page.casino.showtext1") +
          showtotal +
          $t("page.casino.showtext2") +
          games.length +
          $t("page.casino.showtext3")
        }}
      </p>
      <div
        v-if="showNextPage"
        @click="nextPage"
        class="w-[120px] m-auto mt-2 text-center bg-[#2f4553] text-white hover:bg-[#557086] px-4 py-2 rounded cursor-pointer"
      >
        {{ $t("page.casino.more") }}
      </div>
    </div>
  </div>
</template>
<script setup>
import {
  reactive,
  ref,
  onMounted,
  defineAsyncComponent,
  onActivated
} from "vue";
import { gameList, gameCollect, gameCollectList } from "../../api/casion.js";
import { mainAct } from "../../store/activeda";
const Search = defineAsyncComponent(() =>
  import("../../components/search/index.vue")
);
import { useRouter, useRoute } from "vue-router";
import { eventBus } from "@/utils/eventBus";
import { gameDetail } from "@/store/game";

const game = gameDetail();
const router = useRouter();
const route = useRoute();
const main2 = mainAct();

const games = ref([]);
const currentPage = ref(1);
const showtotal = ref(null);
const showNextPage = ref(false);

const getList = async () => {
  let data = {
    page_size: 14,
    page: currentPage.value
  };
  let res = await gameCollectList(data);
  if (res.data && res.data?.list?.length) {
    showtotal.value = res.data?.total;
    if (res.data.total > res.data.page * res.data.page_size) {
      console.log("显示翻页按钮");
      showNextPage.value = true;
    } else {
      showNextPage.value = false;
    }
    res.data.list.forEach(item => {
      if (!item.img_url.startsWith("http")) {
        item.img_url = main2.static_base_url + item.img_url;
      }
    });
    games.value.push(...res.data.list);
    console.log("⬇⬇   ---> 收藏夹列表 <---   ⬇⬇");
    console.log(games.value);
  }
};
const nextPage = async () => {
  currentPage.value += 1;
  getList();
};

const clickStar = async e => {
  console.log(e.code);
  let data = {
    game_code: e.code
  };
  let res = await gameCollect(data);
  console.log(res);
  if (res.errno == 0) {
    //请求收藏夹列表
    currentPage.value = 1;
    games.value = [];
    getList();
  }
};

const addRecent = game => {
  if (!game || !game.id) {
    return;
  }

  console.log("添加的游戏:", game);

  // 检查并初始化 recentList
  if (!Array.isArray(main2.recentList)) {
    console.error("recentList 不是一个有效的数组");
    return;
  }

  // 如果游戏已存在，先移除它，再将其放到最前面
  const existingIndex = main2.recentList.findIndex(item => item.id === game.id);
  if (existingIndex !== -1) {
    main2.recentList.splice(existingIndex, 1);
  }

  // 将新游戏放到最前面
  main2.recentList.unshift(game);

  // 更新当前游戏
  main2.currentGame = game;

  // 去重：根据游戏ID去重，保证唯一性
  main2.recentList = main2.recentList.filter(
    (value, index, self) => index === self.findIndex(t => t.id === value.id)
  );

  // 保证列表长度不超过35条
  if (main2.recentList.length > 35) {
    main2.recentList.splice(35);
  }
};

const clickGame = url => {
  //跳转游戏
  const matchLoginGame = url.match(/login_game/g);
  const loginGame = matchLoginGame ? matchLoginGame[0] : "";
  const matchGameCode = url.match(/game_code=[^&]*/);
  const gameCode = matchGameCode ? matchGameCode[0].split("=")[1] : "";
  //跳转外链
  const matchLink = url.match(/link/g);
  const link = matchLink ? matchLink[0] : "";
  const matchUrl = url.match(/url=[^&]*/);
  const linkurl = matchUrl ? matchUrl[0].split("=")[1] : "";
  if (loginGame != "") {
    if (!main2.isLogin) {
      if (main2._isMobile) {
        router.push("/login");
      } else {
        main2.showLoginLayer("no");
      }
      return;
    }
    game.gameLogin(gameCode, router);
  }
  if (link != "") {
    console.log(link);
    console.log(linkurl);
    window.open(linkurl, "_blank");
  }
};
onMounted(() => {});
onActivated(() => {
  currentPage.value = 1;
  games.value = [];
  getList();
});
</script>
<style scoped lang="less">
@media (max-width: 600px) {
  .gameBox {
    grid-gap: 10px 5px !important;
    grid-template-columns: repeat(3, 1fr) !important;

    .item {
      width: 28vw !important;
      max-width: unset;
      min-width: unset;
    }
    .game_loading_div {
      width: 28vw !important;
      height: 36vw !important;
    }
    .star {
      display: block !important;
    }
    .mb {
      opacity: 1 !important;
    }
  }
}

.gameBox {
  background-color: #1a2c38;
  display: grid;
  grid-gap: 2rem 1rem;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  .hover-img {
    will-change: transform;
    transition: 0.3s;
  }
  .item .game_loading_div {
    width: 157px;
    color: #fff;
    height: 216px;
    cursor: pointer;
    background-color: #213743;
    text-align: center;
    line-height: 216px;
    border-radius: 4px;
  }
  .star {
    display: none;
  }
  .mb {
    opacity: 0;
    transition-duration: 1s;
    transition-property: opacity;
    background: linear-gradient(
      0deg,
      rgba(255, 255, 255, 0) 0%,
      rgba(0, 0, 0, 0.3) 25%,
      rgba(0, 0, 0, 0.5) 60%,
      rgba(48, 48, 48, 0.9) 100%
    );
  }

  .item:hover .hover-img {
    transform: translateY(-4%);
    .star {
      display: block;
      z-index: 12;
    }
    .mb {
      opacity: 1;
      transition-duration: 1s;
      transition-property: opacity;
      z-index: 11;
    }
  }
}
</style>
